/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Addon SDK dependencies */
const _sdkSimplePrefs = require('sdk/simple-prefs');

/* Used modules */
const _pUri = require('./uri');


/* Internal APIs */

/** @public */
const addButtonHandler = (name, handler) => {
	const sdkSimplePrefs = _sdkSimplePrefs;
	if ('function' != typeof handler) {
		throw new TypeError('Not a function');
	}
	try {
		sdkSimplePrefs.on(name + '', () => {
			handler();
		});
	} catch (e) {}
};

/**
	@public
	Does not accept preseeded preferences and only accepts runtime changes (via
	about:addons or about:config). Also resets the value on every restart
	because this is not really a preference (but a file picker).
*/
const addFilePickerHandler = (name, handler) => {
	const sdkSimplePrefs = _sdkSimplePrefs;
	if ('function' != typeof handler) {
		throw new TypeError('Not a function');
	}
	
	name = name + '';
	
	if ('string' != typeof sdkSimplePrefs.prefs[name] && 'undefined' != typeof sdkSimplePrefs.prefs[name] && null !== sdkSimplePrefs.prefs[name]) {
		throw new TypeError('Invalid preference type');
	}
	
	// reset
	sdkSimplePrefs.prefs[name] = '';
	
	try {
		sdkSimplePrefs.on(name + '', () => {
			const pUri = _pUri;
			try {
				const value = sdkSimplePrefs.prefs[name];
				if ('string' != typeof value || '' === value) {
					// called when we reset the preference value!
					throw new TypeError('Ignoring invalid path');
				}
				
				sdkSimplePrefs.prefs[name] = '';
				handler(pUri.filenameToURI('' + value));
			} catch (e) {}
		});
	} catch (e) {}
};


/* Exports */
exports.addButtonHandler = addButtonHandler;
exports.addFilePickerHandler = addFilePickerHandler;


// vim: ts=4 noet ai

